﻿using System.Collections.Generic;
using System.Dynamic;
using System.Linq;
using Orchard.ContentManagement;
using SchoolPointe.Menus.ViewModels;
using SchoolPointe.RelatedContent.Drivers;
using SchoolPointe.RelatedContent.Models;
using SchoolPointe.RelatedContent.Services;
using SchoolPointe.Menus.Models;
using Orchard.ContentManagement.Records;

namespace SchoolPointe.Menus.Drivers.RelatedContentDrivers
{
    public class MenuWidgetMenuDriver : DefaultRelatedContentDriver
    {
        private readonly IContentManager _contentManager;

        public MenuWidgetMenuDriver(IRelatedContentService relatedContentService, IContentManager contentManager)
            : base(relatedContentService, contentManager)
        {
            _contentManager = contentManager;
        }

        public override string ContentType
        {
            get { return "MenuWidget"; }
        }

        public override string RelationshipIdentifier
        {
            get { return "menu"; }
        }

        protected override Orchard.ContentManagement.Drivers.DriverResult Display(RelatedContentRelationship relationship, IEnumerable<ContentItemRecord> relatedItems, string displayType, dynamic shapeHelper)
        {
            if (relatedItems.Any())
            {
                var menu = _contentManager.Get(relatedItems.First().Id);
                var menuShape = _contentManager.BuildDisplay(menu);
                var shape = shapeHelper.Parts_MenuWidget().Add(menuShape);
                return ContentShape("Parts_MenuWidget", () => shape);
            }
            return null;
        }

        protected override Orchard.ContentManagement.Drivers.DriverResult Editor(RelatedContentRelationship relationship, IEnumerable<ContentItemRecord> relatedItems, IUpdateModel updater, dynamic shapeHelper)
        {
            var menus = _contentManager.Query<BetterMenuPart>(VersionOptions.Published, "Menu").List();
            var vm = new MenuWidgetMenuViewModel();
            vm.AvailableMenus = menus;

            if (updater != null)
            {
                updater.TryUpdateModel(vm, Prefix, null, null);
                if (vm.MenuId > 0)
                {
                    SetRelatedItems(new List<int> { vm.MenuId });
                }
            }
            else
            {
                if (relatedItems.Any())
                    vm.MenuId = relatedItems.First().Id;    
            }            

            return ContentShape("MenuWidget_MenuSelector", () =>
                shapeHelper.EditorTemplate(
                    Model: vm,
                    TemplateName: "MenuWidget-MenuSelector",
                    Prefix: Prefix));
        }       
    }
}